<!DOCTYPE html>
<html>
<head>
    <title>Text Gravity</title>
    <style>
        label, input, textarea {
            display: block;
        }
        textarea {
            width: 300px;
            height: 100px;
        }
    </style>
</head>
<body>
<form method="get" action="task3.php">
    <label>Text:</label>
    <textarea name="text">The Milky Way is the galaxy that contains our star system</textarea>
    <label>Line length:</label>
    <input type="text" name="lineLength" value="10"/>
    <input type="submit" value="SUBMIT"/>
</form>
<?php
if (isset($_GET['text']) && isset($_GET['lineLength'])) {
    $text = $_GET['text'];
    $lineLength = $_GET['lineLength'];

    $numberOfRows = strlen($text) / $lineLength;

    if (!is_int($numberOfRows)) {
        $numberOfRows = intval($numberOfRows) + 1;
    }

    $tableArray = array();
    $rowInTable = array();

    for ($cols = 0; $cols < $lineLength; $cols++) {
        array_push($rowInTable, 'empty');
    }

    for ($rows = 0; $rows < $numberOfRows; $rows++) {
        array_push($tableArray, $rowInTable);
    }

    $charIndexer = 0;

    for ($rows = 0; $rows < $numberOfRows; $rows++) {
        for ($cols = 0; $cols < $lineLength; $cols++) {
            if ($text[$charIndexer] !== ' ' && $charIndexer < strlen($text)) {
                $tableArray[$rows][$cols] = $text[$charIndexer];
            }
            else {
                $tableArray[$rows][$cols] = 'empty';
            }

            $charIndexer++;
        }
    }
    for ($rows = $numberOfRows - 1; $rows >= 0; $rows--) {
        for ($cols = 0; $cols < $lineLength; $cols++) {
            $colBrowser = 1;

            if ($tableArray[$rows][$cols] === 'empty') {
                while (true) {
                    if ($tableArray[$rows - $colBrowser][$cols] !== 'empty') {
                        $tableArray[$rows][$cols] = $tableArray[$rows - $colBrowser][$cols];
                        $tableArray[$rows - $colBrowser][$cols] = 'empty';

                        break;
                    }

                    $colBrowser++;
                }
            }
        }
    }

    $result = '<table>';

    for ($rows = 0; $rows < $numberOfRows; $rows++) {
        $result .= "<tr>";

        for ($cols = 0; $cols < $lineLength; $cols++) {
            if (ord($tableArray[$rows][$cols]) === 0) {
                $result .= "<td> </td>";
            }
            else {
                $result .= "<td>" . htmlspecialchars($tableArray[$rows][$cols]) . "</td>";
            }
        }

        $result .= "</tr>";
    }

    $result .= '<table>';

    echo $result;
}
?>
</body>
</html>